<template>
<div>
<transition name='moveR'>
<div class="player" v-show="fullScreen">
  <div class="normal-player">
    <div class="song-tit">
      <van-icon @click="fanhui" class="fanhui" name="arrow-left"></van-icon>
      <div class="name" v-html="currentSong.name"></div>
      <div class="singer" v-html="currentSong.singer"></div>
    </div>
    <div
      @click="songImgClick"
      v-show="!alllyric"
      class="cover_container"
      :class="cdCls"
      style="background-image: url(http://music.championhua.club/img/disc.png);">
      <img
        @touchstart.prevent="touchImgLongTime"
        @touchmove.prevent="touchImgMove"
        @touchend="touchImgEnd"
        :src="currentSong.image">
    </div>
    <transition name='fade'>
      <image-show @Imgclick="Imgclick" v-show="showImg" :currentSong="currentSong"></image-show>
    </transition>
    <audio
      @timeupdate="timeUpdate"
      @canplay="ready"
      @error="error"
      @ended="ended"
      ref="audio"
      :src="currentSong.url">
    </audio>
    <div class="progress-wrapper"><span class="time time-l">{{resetCurrtTime(currentTime)}}</span>
      <div class="progress-bar-wrapper">
        <div @click="progressBarClick" ref="proBar" class="progress-bar">
          <div class="bar-inner">
            <div ref="progress" class="progress"></div>
             <div class="progress-btn-wrapper">
               <div
                 ref="btn"
                 @touchstart.prevent="_touchstart"
                 @touchmove.prevent="_touchmove"
                 @touchend="_touchend"
                 class="progress-btn">
                 </div>
             </div>
            </div>
        </div>
      </div>
      <span class="time time-r">{{resetCurrtTime(duration)}}</span>
    </div>
    <lyrics
      @alllyricClick="alllyricClick"
      :alllyric="alllyric"
      :currentTime="currentTime"
      :currentLyric="currentLyric">
      </lyrics>
    <div class="kognzhianniu">
      <a class="btn_pause" @click="togglePlaying"><span ref="cover"></span></a>
      <a class="btn_play play_left" @click="prve"><span></span></a>
      <a class="btn_play play_right" @click="next"><span></span></a>
      <a class="btn_mode play_mode" @click="change_mode"><span ref="mode"></span></a>
      <a class="play_current_list" @click="currentList"><span></span></a>
    </div>
    <div ref="dialog" style="display: none;"><dia-log :text="text"></dia-log></div>
    <van-popup v-model="show" position="bottom" :style="{ height: '60%' }" round>
      <ul>
        <li
          @click="currentListSongClick(index)"
          class="play_current_list_li"
          v-for="(song,index) in currentPlayList"
          :key="index">
          <img class="currentImg" v-show="currentIndex===index" src="../../common/imgs/laba.png"/>
          <div :class="{'red':currentIndex === index}">{{song.name}}
            <span :class="{'red':currentIndex === index}">- {{song.singer}}</span>
          </div>
          <div @click.stop="deleted(index)" class="delete"></div>
        </li>
      </ul>
    </van-popup>
    <div class="bg" :style="{backgroundImage: 'url(' + currentSong.image + ')'}"></div>
  </div>
</div>
</transition>
</div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import {Icon, Popup} from 'vant'
import diaLog from 'base/diaLog'
import ImageShow from 'base/ImageShow'
import { getLyric, getMiguLyric } from 'api/lyric'
import base64url from 'base64url'
import Lyric from 'lyric-parser'
import lyrics from 'base/lyrics'

export default {
  name: 'player',
  data () {
    return {
      isReady: false,
      currentTime: 0,
      duration: '',
      text: '',
      show: false,
      currentPlayList: [],
      showImg: false,
      currentLyric: null, // 设置一个歌词维护属性
      lyric: '',
      alllyric: false
    }
  },
  created() {
    this.touch = {}
  },
  mounted() {
  },
  components: {
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    diaLog,
    ImageShow,
    lyrics
  },
  computed: {
    ...mapGetters([
      'playList',
      'fullScreen',
      'currentSong',
      'singer',
      'playing',
      'currentIndex',
      'mode'
    ]),
    cdCls () {
      return this.playing ? 'play' : 'play pause'
    }
  },
  watch: {
    // 监听播放器的展示状态
    fullScreen () {
      if (this.fullScreen) {
        this.currentPlayList = this.playList
      }
    },
    // 监听当前播放歌曲的变化
    currentSong () {
      this.$nextTick(() => {
        this.$refs.audio.play()
      })
      if (this.currentSong.singer.indexOf('咪咕') > -1) {
        getMiguLyric(this.currentSong.mid).then((res) => {
          let lyric = res.lyric
          this.currentLyric = new Lyric(lyric, this.handleLyric)
        })
        return
      }
      // 获取歌词
      getLyric(this.currentSong.mid).then((res) => {
        let lyric = base64url.decode(res.lyric)
        this.currentLyric = new Lyric(lyric, this.handleLyric)
        // console.log(this.currentLyric)
      })
    },
    // 监听歌曲playing状态，播放或暂停歌曲并改变播放暂停按钮状态
    playing (newPlaying) {
      var audio = this.$refs.audio
      this.$nextTick(() => {
        newPlaying ? audio.play() : audio.pause()
        if (newPlaying === true) {
          this.$refs.cover.style.backgroundPositionY = '-50px'
        } else {
          this.$refs.cover.style.backgroundPositionY = '0'
        }
      })
    },
    // 监听歌曲播放进度的变化，改变进度条的位置
    currentTime () {
      if (!this.touch.start) {
        var barlen = this.$refs.proBar.offsetWidth - this.$refs.btn.offsetWidth
        var traX = this.currentTime / this.currentSong.duration * barlen
        this._offsetWidth(traX)
      }
    }
  },
  methods: {
    // 控制多行歌词的展示和隐藏
    alllyricClick () {
      this.alllyric = false
    },
    songImgClick () {
      this.alllyric = true
    },
    // 图片长按展示
    touchImgLongTime () {
      clearTimeout(this.touch.timeOutEvent)
      this.touch.timeOutEvent = 0
      this.touch.timeOutEvent = setTimeout(() => {
        this.showImg = true
      }, 500)
    },
    touchImgEnd () {
      clearTimeout(this.touch.timeOutEvent)
    },
    touchImgMove () {
      clearTimeout(this.touch.timeOutEvent)
    },
    Imgclick () {
      this.showImg = false
    },
    // 删除当前列表中的某首歌
    deleted(index) {
      this.currentPlayList.splice(index, 1)
      // 当删除的歌曲的index值小于当前播放的index值时
      if (index < this.currentIndex) {
        this.setCurrentIndex(this.currentIndex - 1)
        this.setPlaying(true)
      }
      this.setPlaying(true)
    },
    // 点击当前列表歌曲播放
    currentListSongClick(index) {
      this.setCurrentIndex(index)
      this.setPlaying(true)
    },
    // 右下角列表点击
    currentList() {
      this.show = true
    },
    // 进度条点击事件
    progressBarClick (e) {
      this._offsetWidth(e.offsetX)
      var newCurrentTime = e.offsetX / this.$refs.proBar.offsetWidth * this.currentSong.duration
      if (newCurrentTime > this.currentSong.duration) {
        newCurrentTime = this.currentSong.duration
      }
      this.$refs.audio.currentTime = newCurrentTime
    },
    // 当歌曲播放结束时
    ended () {
      if (this.mode === 0) {
        this.$refs.audio.play()
      } else if (this.mode === 2) {
        this.setCurrentIndex(this.currentIndex + 1)
        this.$refs.audio.play()
      } else {
        let index = Math.floor(Math.random() * this.playList.length)
        this.setCurrentIndex(index)
        this.$refs.audio.play()
      }
    },
    // 播放模式点击页面效果
    change_mode () {
      if (this.mode === 0) {
        // 随机播放
        let mode = this.mode + 1
        this.setPlayMode(mode)
        this.$refs.mode.style.backgroundPositionY = '-72px'
        this.text = '随机播放'
        this.$refs.dialog.style.display = 'block'
        this._setTimeOut()
      } else if (this.mode === 1) {
        // 顺序播放
        let mode = this.mode + 1
        this.setPlayMode(mode)
        this.$refs.mode.style.backgroundPositionY = '-204px'
        this.text = '顺序播放'
        this.$refs.dialog.style.display = 'block'
        this._setTimeOut()
      } else if (this.mode === 2) {
        // 单曲循环
        let mode = 0
        this.setPlayMode(mode)
        this.$refs.mode.style.backgroundPositionY = '-231px'
        this.text = '单曲循环'
        this.$refs.dialog.style.display = 'block'
        this._setTimeOut()
      }
    },
    // 页面弹出层在500毫秒后隐藏
    _setTimeOut () {
      window.setTimeout(() => {
        this.$refs.dialog.style.display = 'none'
      }, 500)
    },
    // progressBar拖动事件
    _touchstart(e) {
      this.touch.start = true
      this.touch.clientX = e.changedTouches[0].clientX
      this.touch.left = this.$refs.progress.clientWidth
    },
    _touchmove(e) {
      if (!this.touch.start) {
        return
      }
      this.touch.moveto = e.changedTouches[0].clientX
      var change = this.touch.moveto - this.touch.clientX
      var panyiliang = this.touch.left + change
      var barlen = this.$refs.proBar.offsetWidth - this.$refs.btn.offsetWidth
      if (panyiliang > barlen) {
        panyiliang = barlen
      }
      var persent = Math.max(0, panyiliang)
      this._offsetWidth(persent)
      this.touch.play = persent / barlen * this.currentSong.duration
    },
    // 拖动结束后改变歌曲播放位置
    _touchend() {
      this.touch.start = false
      this.$refs.audio.currentTime = this.touch.play
    },
    // 改变progerssBar和进度条的实时位置
    _offsetWidth(offsetwidth) {
      this.$refs.btn.style.transform = `translate3d(${offsetwidth}px, 0px, 0px)`
      this.$refs.progress.style.width = `${offsetwidth}px`
    },
    // 获取audio播放到的位置
    timeUpdate(e) {
      this.currentTime = e.target.currentTime
    },
    // 给获取的时间重新设置格式
    resetCurrtTime(time) {
      var currentTime = Math.floor(time)
      var min = Math.floor(currentTime / 60)
      var sec = Math.floor(currentTime % 60)
      if (sec < 10) {
        sec = '0' + sec
      }
      return `${min}:${sec}`
    },
    error() {
      this.isReady = true
    },
    ready () {
      this.isReady = true
      this.duration = Math.floor(this.$refs.audio.duration)
    },
    // 上一首按钮点击事件
    prve () {
      if (!this.isReady) {
        return
      }
      // mode为随机播放时
      if (this.mode === 1) {
        let index = Math.floor(Math.random() * this.playList.length)
        this.setCurrentIndex(index)
      }
      var index = this.currentIndex - 1
      if (index === -1) {
        index = this.playList.length - 1
      }
      this.setCurrentIndex(index)
      if (!this.playing) {
        this.togglePlaying()
      }
      this.isReady = false
      this.currentTime = 0
    },
    // 下一首按钮点击事件
    next () {
      if (!this.isReady) {
        return
      }
      // mode为随机播放时
      if (this.mode === 1) {
        let index = Math.floor(Math.random() * this.playList.length)
        this.setCurrentIndex(index)
      }
      var index = this.currentIndex + 1
      if (index === this.playList.length) {
        index = 0
      }
      this.setCurrentIndex(index)
      if (!this.playing) {
        this.togglePlaying()
      }
      this.isReady = false
      this.currentTime = 0
    },
    // 播放器左上角返回按键点击事件
    fanhui () {
      var flag = false
      this.setFunScreen(flag)
    },
    //
    togglePlaying () {
      if (!this.isReady) {
        return
      }
      this.setPlaying(!this.playing)
    },
    ...mapMutations({
      setFunScreen: 'SET_FULL_SCREEN',
      setPlaying: 'SET_PLAYING_STATE',
      setCurrentIndex: 'SET_CURRENT_INDEX',
      setPlayMode: 'SET_PLAY_MODE',
      setPlayList: 'SET_PLAYLIST'
    })
  }
}
</script>

<style scoped="scoped">
  .currentImg{
    width: 0.6rem;
    float: left;
    margin-top: 0.4rem;
    margin-right: 3px;
   }
  .red{
    color: red!important;
  }
  .play_current_list_li {
    height: 1.4rem;
    line-height: 1.4rem;
    font-size: .4rem;
    margin-left: 5%;
    border-bottom: 1px solid #eee;
    color: black;
    width: 95%;
  }
  .play_current_list_li div{
    width: 80%;
    float: left;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .play_current_list_li span{
    font-size: .35rem;
    color: #999;
  }
  .play_current_list_li .delete{
    float: right;
    width: 1rem;
    height: 1rem;
    background: url(http://music.championhua.club/img/delect.png);
    background-position-y: -3.9rem;
    background-size: 5rem;
    margin-top: .2rem;
    position: relative;
    right: .5rem;
  }
  .player{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    background: white;
  }
  .player .song-tit {
    color: white;
    margin: 0 20px;
    padding-top: 10px;
    padding-bottom: 10px;
    text-align: center;
    line-height: 20px;
    position: relative;
    z-index: 3;
  }
  .player .song-tit .name {
    font-size: .5rem;
    overflow: hidden;
    display: block;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 80%;
    margin: 0 auto;
  }
  .normal-player {
    position: relative;
    width: 100%;
    height: 100%;
  }
  .fanhui{
    position: absolute;
    left: -5%;
    top: 10%;
    padding: 3%;
  }
  .player .song-tit .singer {
    font-size: .4rem;
    position: relative;
    white-space: nowrap;
    max-width: 52%;
    overflow: hidden;
    text-overflow: ellipsis;
    margin: 0 auto;
  }
.bg {
    background-color: #161824;
    background-position: 50%;
    background-repeat: no-repeat;
    background-size: auto 100%;
    -webkit-transform: scale(1.5);
    -ms-transform: scale(1.5);
    transform: scale(1.3);
    -webkit-transform-origin: center top;
    -ms-transform-origin: center top;
    transform-origin: center top;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    height: 100%;
    overflow: hidden;
    z-index: -1;
    -webkit-transition: opacity .3s linear;
    transition: opacity .3s linear;
    z-index: 1;
    webkit-filter: blur(15px);
    filter: blur(15px);
}
.bg:before{
  content: " ";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background-color: rgba(0,0,0,.5);
}
.cover_container {
   position: fixed;
   width: 6rem;
   margin: 0 auto;
   z-index: 3;
   top: 50%;
   left: 50%;
   height: 6rem;
   background-size: 6rem;
   margin-top: -4rem;
   margin-left: -3rem;
}
.cover_container img {
  display: block;
  width: 4rem;
  background: #fff;
  border-radius: 50%;
  height: 4rem;
  position: relative;
  top: 1rem;
  left: 1rem;
}
.play {
  animation: rotate 20s linear infinite;
}
.pause {
  animation-play-state: paused;
}
@keyframes rotate{
  0% {
    transform: rotate(0);
  }
  100%{
    transform: rotate(360deg);
  }
}
.kognzhianniu{
  position: absolute;
  bottom: 0;
  width: 100%;
  display: block;
  overflow: hidden;
  height: 80px;
}
.kognzhianniu .btn_play, .kognzhianniu .btn_pause, .kognzhianniu .btn_mode {
    position: absolute;
    left: 50%;
    z-index: 10;
    width: 46px;
    height: 46px;
    overflow: hidden;
    margin-left: -23px;
    bottom: 30px;
}
.kognzhianniu .btn_play span, .kognzhianniu .btn_pause span {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    width: 46px;
    height: 46px;
    line-height: 999em;
    background: url(../../common/imgs/sprite_page_play.png) no-repeat;
    background-size: 50px 200px;
}
.kognzhianniu .play_left {
    left: 30%;
    width: 40px;
    height: 40px;
    margin-left: -20px;
}
.kognzhianniu .play_left span {
   width: 40px;
   height: 40px;
   background: url(../../common/imgs/play_prev.png) no-repeat;
   background-size: 100%;
}
.kognzhianniu .play_right {
  left: 70%;
  width: 40px;
  height: 40px;
  margin-left: -20px;
}

.kognzhianniu .play_right span {
  width: 40px;
  height: 40px;
  background: url(../../common/imgs/play_next.png) no-repeat;
  background-size: 100%;
}
.kognzhianniu .play_mode {
  left: 10%;
  width: 26px;
  height: 24px;
  margin-left: -13px;
  bottom: 48px;
  margin-bottom: -12px;
}
.kognzhianniu .play_mode span, .kognzhianniu .play_current_list span{
  position: absolute;
  width: 26px;
  height: 24px;
  background: url(../../common/imgs/player.png) no-repeat 0 -229px;
}
.kognzhianniu .play_current_list {
    right: 10%;
    width: 22px;
    height: 24px;
    margin-right: -11px;
    bottom: 48px;
    margin-bottom: -12px;
    position: absolute;
    z-index: 10;
    overflow: hidden;
}
.kognzhianniu .play_current_list span {
  background-position: 0 -258px;
}
.progress-wrapper {
    display: flex;
    align-items: center;
    width: 80%;
    margin: 0 auto;
    padding: 10px 0;
    z-index: 4;
    position: absolute;
    bottom: 90px;
    left: 10%;
}
.time{
    color: #fff;
    font-size: 12px;
    -webkit-box-flex: 0;
    -ms-flex: 0 0 30px;
    flex: 0 0 30px;
    line-height: 30px;
    width: 30px;
}
.time-l{
  text-align: left;
}
.progress-bar-wrapper {
  flex: 1;
}
.progress-bar{
    height: 30px;
}
.progress-bar .bar-inner .progress-btn-wrapper {
    position: absolute;
    left: -8px;
    top: -13px;
    width: 30px;
    height: 30px;
}
.progress-bar .bar-inner .progress-btn-wrapper .progress-btn {
    position: relative;
    top: 7px;
    left: 7px;
    box-sizing: border-box;
    width: 16px;
    height: 16px;
    border: 3px solid #fff;
    border-radius: 50%;
    background: #ffcd32;
}
.progress-bar .bar-inner{
    position: relative;
    top: 13px;
    height: 4px;
    background: #ebedf0;
}
.progress{
  background: #99999A;
  height: 100%;
}
.time-r{
  text-align: right;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s
}
.fade-enter, .fade-leave-to{
  opacity: 0;
}
/*进场和出场动画*/
.moveR-enter-active,  .moveR-leave-active {
  transition: all 0.3s linear;
  transform: translateX(0);
}
.moveR-enter,  .moveR-leave {
  transform: translateX(100%);
}
.moveR-leave-to{
  transform: translateX(100%);
}
</style>
